Mountain Bike (MTB) Categorization Analysis
Introduction
Project Overview
For this project, our team will determine whether the specifications of mountain bikes (MTB) are enough to differentiate between the different types of mountain bike categories.
Currently, full suspension mountain bikes come in multiple categories:
- Cross Country (XC) | Tend to be the most lightweight, nimble, and designed to put the rider in an efficient pedaling position
- Enduro (EN) | Heavier frames, more travel and more downhill oriented geometry
- Trail (TR) | The most common category of bikes, considered to be the halfway point between XC and Enduro
- All Mountain (AM) | A more niche category which some manufacturers claim to be more downhill focused than trail bikes, but not designed for downhill races like Enduro bikes are
- Downcountry (DC) | A relatively new category between XC and Trail. Similar to the All Mountain category, these bikes aren’t race specific like XC bikes tend to be, but are lighter and faster than trail bikes.
With all of the factors to consider when designing a bike, there are no clear boundaries between these categories. For example, one brand’s Downcountry bike could be what another brand considers a Trail bike. The popular mountain biking website PinkBike has done in depth analyses of many bikes across all categories, and the topic as to which category bikes fall in and how many categories is too many often comes up, as seen in the video here.
The goal of our project is to determine how many, if any, discrete categories should exist for mountain bikes. Since most specifications and geometric measurements have one direction when moving across the spectrum of bikes, it’s reasonable to believe that these measurements could be reduced to much fewer dimensions, and perhaps even one continuous principle component rather than discrete categories. Here is a diagram of some of the different types of geometric specifications on mountain bikes:
Various Dimension Features of a Bike’s Geometry
The Data
The data was retrieved manually from each of the mountain bike company’s websites. Let’s take a look at the data.
# Read in sheet 2 of our data
mtb_data <- read_excel(here::here('Data/mtb_stats.xlsx'), 'Sheet1')
mtb_data <- mtb_data %>%
# Clean up the label column
mutate(label = str_replace_all(str_to_lower(label), '[:punct:]', ''),
# Create a feature for the long-version of the names
bike_category = case_when(
label == 'tr' ~ 'Trail',
label == 'xc' ~ 'Cross Country',
label == 'dc' ~ 'Downcountry',
label == 'am' ~ 'All Mountain',
label == 'en' ~ 'Enduro',
TRUE ~ 'red'
))
# Pull out the class labels
labels <- mtb_data %>%
select(label)
# Let's view the mtb_data output
# In any kable outputs, display NAs as blanks
opts <- options(knitr.kable.NA = "")
mtb_data %>%
head(25) %>%
# Fix up the headers by replacing the underscores with spaces
rename_all(funs(str_replace_all(., "_", " "))) %>%
# Make everything proper capitalization
# rename_all(funs(str_to_title)) %>%
kable() %>%
kable_styling(bootstrap_options = c("striped", "hover"),
full_width = F,
font_size = 12) %>%
# Make the header row bold and black so it's easier to read
row_spec(0, bold = T, color = "black") %>%
scroll_box(height = "400px", width = "100%")| model | brand | build type | price | url | image | setting | size used | label | rear travel | fork travel | f piston | f rotor dim | r piston | r rotor dim | head angle | seat angle | crank length | stem length | handlebar width | reach | stack | wheelbase | chainstay length | bb height | standover height | bike category |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| habit | cannondale | L | tr | 130 | 140 | 4 | 180 | 4 | 180 | 66.0 | 74.5 | 780 | 460.0 | 625.0 | 1210.0 | 435.0 | 339.0 | 770.0 | Trail | |||||||
| scalpel | cannondale | L | xc | 100 | 100 | 2 | 160 | 2 | 160 | 68.0 | 74.5 | 80 | 760 | 435.0 | 601.0 | 1175.0 | 436.0 | 331.0 | 745.0 | Cross Country | ||||||
| scalpel se | cannondale | L | dc | 120 | 120 | 2 | 160 | 2 | 160 | 67.0 | 74.0 | 780 | 450.0 | 611.0 | 1172.0 | 436.0 | 344.0 | 758.0 | Downcountry | |||||||
| reign advanced pro | giant | L | en | 146 | 170 | 4 | 203 | 4 | 203 | 64.6 | 76.4 | 40 | 800 | 488.0 | 631.0 | 1262.0 | 439.0 | 781.0 | Enduro | |||||||
| trance advanced X pro | giant | high | L | tr | 135 | 150 | 4 | 203 | 4 | 180 | 66.2 | 77.9 | 50 | 800 | 494.0 | 624.0 | 1238.0 | 435.0 | 761.0 | Trail | ||||||
| trance advanced X pro | giant | low | L | tr | 135 | 150 | 4 | 203 | 4 | 180 | 65.5 | 77.2 | 50 | 800 | 486.0 | 631.0 | 1239.0 | 438.0 | 752.0 | Trail | ||||||
| anthem advanced pro | giant | L | xc | 90 | 100 | 2 | 180 | 2 | 160 | 69.0 | 73.5 | 80 | 780 | 454.0 | 594.0 | 1154.0 | 438.0 | 817.0 | Cross Country | |||||||
| jet 9 rdo | niner | high | M | tr | 120 | 130 | 4 | 180 | 4 | 180 | 66.5 | 76.0 | 40 | 800 | 450.0 | 613.0 | 1179.0 | 430.0 | 698.0 | Trail | ||||||
| jet 9 rdo | niner | low | M | tr | 120 | 130 | 4 | 180 | 4 | 180 | 66.0 | 75.5 | 40 | 800 | 444.0 | 617.0 | 1180.0 | 432.0 | 705.0 | Trail | ||||||
| rip 0 rdo | niner | high | M | tr | 140 | 150 | 4 | 180 | 4 | 180 | 66.0 | 75.8 | 800 | 440.0 | 615.0 | 1181.0 | 435.0 | 712.0 | Trail | |||||||
| rip 0 rdo | niner | low | M | tr | 140 | 150 | 4 | 180 | 4 | 180 | 65.0 | 75.2 | 800 | 433.0 | 619.0 | 1182.0 | 435.0 | 705.0 | Trail | |||||||
| rkt 9 rdo | niner | M | dc | 90 | 120 | 4 | 180 | 4 | 160 | 70.0 | 73.5 | 780 | 413.0 | 617.0 | 1111.0 | 439.0 | 739.0 | Downcountry | ||||||||
| rkt 9 rdo rs | niner | M | xc | 90 | 100 | 4 | 180 | 4 | 160 | 71.0 | 74.5 | 780 | 424.0 | 600.0 | 1103.0 | 439.0 | 728.0 | Cross Country | ||||||||
| megatower | santa cruz | L | en | 160 | 160 | 4 | 200 | 4 | 200 | 65.0 | 76.6 | 470.0 | 625.0 | 1231.0 | 435.0 | 343.0 | 713.0 | Enduro | ||||||||
| tallboy | santa cruz | L | tr | 120 | 130 | 4 | 180 | 4 | 180 | 65.7 | 76.4 | 50 | 800 | 470.0 | 619.0 | 1211.0 | 430.0 | 335.0 | 706.0 | Trail | ||||||
| hightower | santa cruz | L | tr | 145 | 150 | 4 | 180 | 4 | 180 | 65.5 | 76.8 | 50 | 780 | 473.0 | 619.0 | 1231.0 | 433.0 | 344.0 | 717.0 | Trail | ||||||
| blur | santa cruz | L | xc | 100 | 100 | 2 | 160 | 2 | 160 | 69.0 | 74.0 | 750 | 460.0 | 598.0 | 1160.0 | 432.0 | 328.0 | 723.0 | Cross Country | |||||||
| blur tr | santa cruz | L | dc | 115 | 120 | 2 | 180 | 2 | 180 | 67.1 | 74.9 | 175 | 60 | 760 | 457.5 | 606.5 | 1183.2 | 435.8 | 339.6 | 745.4 | Downcountry | |||||
| ransom | scott | L | en | 170 | 170 | 4 | 203 | 4 | 180 | 64.5 | 75.0 | 50 | 800 | 466.5 | 627.6 | 1249.2 | 437.9 | 353.0 | 760.9 | Enduro | ||||||
| spark | scott | L | tr | 120 | 130 | 4 | 180 | 4 | 180 | 67.2 | 73.8 | 70 | 760 | 460.0 | 602.4 | 1182.8 | 438.0 | 327.0 | 778.0 | Trail | ||||||
| genius | scott | high | L | tr | 150 | 150 | 4 | 203 | 4 | 180 | 65.6 | 75.3 | 50 | 780 | 472.0 | 609.2 | 1230.8 | 436.0 | 340.0 | 749.5 | Trail | |||||
| genius | scott | low | L | tr | 150 | 150 | 4 | 203 | 4 | 180 | 65.0 | 74.8 | 50 | 780 | 466.1 | 613.7 | 1232.1 | 438.0 | 345.9 | 758.4 | Trail | |||||
| spark rc | scott | L | xc | 100 | 110 | 2 | 180 | 2 | 160 | 68.5 | 73.8 | 80 | 740 | 456.8 | 596.2 | 1158.6 | 435.0 | 319.5 | 756.0 | Cross Country | ||||||
| epic evo | specialized | high | M | dc | 110 | 120 | 4 | 180 | 4 | 160 | 67.0 | 74.5 | 175 | 60 | 760 | 436.0 | 597.0 | 1164.0 | 438.0 | 339.0 | 781.0 | Downcountry | ||||
| epic evo | specialized | low | M | dc | 110 | 120 | 4 | 180 | 4 | 160 | 66.5 | 74.5 | 175 | 60 | 760 | 436.0 | 597.0 | 1164.0 | 438.0 | 336.0 | 781.0 | Downcountry |
EDA
In this section, we’ll take a look at the 74 mountain bikes in our dataset and some of the 27 features. We’ll try to break down our understanding of the data in terms of label, our target variable that acts as the category for each mountain bike.
Label (Mountainbike Category)
As stated earlier, there are 5 mountain bike categories in our dataset:
- Cross Country (xc)
- Enduro (en)
- Trail (tr)
- All Mountain (am)
- Downcountry (dc)
Let’s look at how many of each we have in our dataset.
mtb_data %>%
group_by(bike_category) %>%
tally() %>%
arrange(desc(n)) %>%
# Start our visualization, creating our groups by party affiliation
ggplot(aes(y = forcats::fct_reorder(bike_category, n), x = n)) +
geom_col(fill = "slateblue", na.rm = T) +
# Add a label by recreating our data build from earlier
geom_label(aes(label = n),
size = 5,
# Scooch the labels over a smidge
hjust = .25) +
# Let's change the names of the axes and title
xlab("Number of Bikes") +
ylab("Category (label)") +
labs(title = "Number of Mountain Bikes per Category")We see that out of our 74 bikes, most of them are Trail bikes, with the smallest grouping of bikes being all mountain bikes
Categorical Variables
There are 4 categorical variables we’ll take a look at to better understand our data:
- Setting
- Size
- Front Piston (
f_piston)
- Rear Piston (
r_piston)
mtb_data %>%
select(-label, -bike_category) %>%
DataExplorer::plot_bar(ggtheme = theme_classic(),
title = 'Distribution of Categorical Variables',
theme_config = theme(plot.title = element_text(hjust = 0,
color = "slateblue4",
size = 24),
plot.subtitle = element_text(hjust = 0, color = "slateblue2", size = 10),
plot.caption = element_text(color = "dark gray", size = 10, face = "italic"),
axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14)),
maxcat = 15,
ncol = 2)- We see that only few bikes have a setting value, which is a feature that allows a rider to slightly adjust the frame’s geometry to hone in rider comfort. Later on, we’ll group by settings for the same bike and average the results to get a more accurate representation of the bikes’ specs.
- Most of the bikes analyzed have 4 rear/front pistons. The two variables seem to be perfectly in-sync, leading us to believe that they’re highly correlated.
But, really, we care about understanding how these different variables interact with our target variable, label. Let’s look at their distribution and look for any patterns.
mtb_data %>%
DataExplorer::plot_bar(ggtheme = theme_classic(),
by = 'label',
by_position = 'fill',
title = 'Distribution of Categorical Variables',
theme_config = theme(plot.title = element_text(hjust = 0,
color = "slateblue4",
size = 24),
plot.subtitle = element_text(hjust = 0, color = "slateblue2", size = 10),
plot.caption = element_text(color = "dark gray", size = 10, face = "italic"),
axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14)),
maxcat = 15,
ncol = 2)Here we see:
- The size used for most of the bikes is pretty evenly distributed. For the most part, we attempted to find bikes that are sized to the heights of the authors of this report (approx. 5’8”-5’11”), which tended to be Large-sized bikes; however, for some bikes, like Trail, the specific bike’s company website from which we pulled the data recommended a Medium-sized bike.
- Although most of the bikes have 4-piston brakes, of the bikes that have 2 pistons, most are Cross Country (xc) bikes. 4-piston brakes are known to have higher stopping power which is more important the more the rider intends to ride downhill. However, they come at the cost of additional weight, which most XC riders will avoid at all costs.
Continuous Variables
To analyze the continuous features within our dataset, we built density plots for each of them to better understand their distribution.
DataExplorer::plot_density(mtb_data,
ggtheme = theme_classic(),
title = 'Distribution of Continuous Variables',
geom_density_args = list(fill = 'slateblue'),
theme_config = theme(plot.title = element_text(hjust = 0,
color = "slateblue4",
size = 24),
plot.subtitle = element_text(hjust = 0, color = "slateblue2", size = 10),
plot.caption = element_text(color = "dark gray", size = 10, face = "italic"),
axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14)),
ncol = 3)~Normally Distributed Variables:
- Chainstay_length
- Fork_travel
- Bb_height
- Seat_angle
Skewed Variables:
- Head_angle (skewed right)
- Handlebar_width (skewed left)
- Wheelbase (skewed left)
Multi-Modal Distributed Variables:
- f_rotor_dim / r_rotor_dim
- Stem_length
Like we did for continuous variables, let’s look at the distribution of each of these predictors by our target variable, label, to look for any discernible patterns.
mtb_data %>%
DataExplorer::plot_boxplot(by = 'label',
geom_boxplot_args = list('fill' = 'slateblue'),
ggtheme = theme_classic(),
theme_config = theme(plot.title = element_text(hjust = 0,
color = "slateblue4",
size = 24),
plot.subtitle = element_text(hjust = 0, color = "slateblue2", size = 10),
plot.caption = element_text(color = "dark gray", size = 10, face = "italic"),
axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14)),
ncol = 3)Here we see:
- Cross Country (xc) bikes tend to have the largest head angle and smallest seat angle compared to other bikes. They also have the largest stem length by a significant margin. Overall, Cross Country bikes tend to be the most differentiable from other bike categories;
- All Mountain (am) bikes have a significantly smaller standover height and, along with Enduro (en) bikes, have a much larger reach than other bike categories;
- As is generally expected, Trail (tr) bikes tend to fit mostly in the middle for most of these continuous’ variables. This makes sense given that they tend to split the difference between Cross Country and Enduro bikes.
Average bikes by flip-chip setting
Because some bikes’ websites would have two different “settings” for the same-sized bike, we opted to include both options and average the two together to get one middle-of-the-road estimate for that type of bike.
# Split data based on setting vs. no setting
no_setting <- mtb_data %>%
filter(is.na(setting))
setting <- mtb_data %>%
filter(!is.na(setting))
setting <- cbind(setting$model, setting$label, select_if(setting, is.numeric))
setting$model <- setting$`setting$model`
setting <- setting %>% select(-`setting$model`)
setting$label <- setting$`setting$label`
setting <- setting %>% select(-`setting$label`)
mean_by_setting <- aggregate(x=select(setting, -c(model, label)),
by=list(setting$model, setting$label),
FUN=mean)
mean_by_setting$model <- mean_by_setting$Group.1
mean_by_setting$label <- mean_by_setting$Group.2
mean_by_setting <- mean_by_setting %>% select(-c(Group.1, Group.2))
no_setting <- cbind(no_setting$model, no_setting$label, select_if(no_setting, is.numeric))
no_setting$model <- no_setting$`no_setting$model`
no_setting <- no_setting %>% select(-`no_setting$model`)
no_setting$label <- no_setting$`no_setting$label`
no_setting <- no_setting %>% select(-`no_setting$label`)
new_mtb_data <- data.frame(rbind(mean_by_setting, no_setting))
rownames(new_mtb_data) <- new_mtb_data$model
rm(no_setting)
rm(mean_by_setting)Because some bikes’ websites would have two different “settings” for the same-sized bike, we opted to include both options and average the two together to get one middle-of-the-road estimate for that type of bike. We end up performing this operation for 47% of the bikes in our dataset.
Methodology
Now that we have a better understanding of our mountain bike dataset, we’ll formulate a plan to prove the following hypothesis:
Applying our own clustering algorithms will either give us a different set number of clusters (rather than the 5 pre-ordained categories) OR will not provide clearly defined clusters, leading us to believe that the bikes are actually created on a spectrum and cannot be grouped into one of the 5 pre-ordained categories.
To do so, we’ll:
- Try to use various methods to reduce the featureset and see if there are certain variables that can better be used to differentiate between different mountain bike categories. - Apply various clustering and classification algorithms, including K-Means Clustering, Gaussian Mixture Models, and Multi-class Support Vector Machine, to disprove the notion that 5 distinct categories of Mountain Bikes exist.
Variation Amongst Featureset
The first thing we’ll do is look to see if any of the features in our dataset are better at explaining the variation amongst the different bikes than other features. That is, it’s completely possible that two features are similar and don’t have much variation in them, even across some of the different bike categories. To do so, we’ll:
- Look for highly correlated features and flag these for potential removal;
- Run Principal Component Analysis (PCA) to see if certain features are better at explaining the variation in our data better than others.
1. Correlation
First, let’s take a look at our most highly correlated features. We’ll use the corrplot() function to better order the highly correlated features by the angular order of their eigenvectors.
mtb_correlation <- mtb_data %>%
# Get rid of price for now
select(-price) %>%
# Select our variables of interest
select_if(is.numeric) %>%
# Remove rows with NAs in them
# drop_na() %>%
# Build our correlation matrix, such that missing values are handled by casewise deletion
cor(use = 'complete.obs')
# Convert our results into a tibble for easier manipulation
mtb_correlation_df <- mtb_correlation %>%
as_tibble() %>%
mutate(variable = colnames(mtb_correlation)) %>%
relocate(variable, everything())
# Build our correlation plot, using the angular order of the eigenvectors
corrplot(mtb_correlation,
diag = F,
col = COL2('PRGn'),
tl.col = 'slateblue4',
type = 'lower',
method = 'color',
order = 'AOE',
title = 'Mountain Bike Feature Correlation'
)Here we see some obvious correlations, for example:
f_piston(front brakes) is perfectly correlated withr_piston(rear brakes), which makes sense since mountain bikes tend to use the same types/spec of brakes for the front vs. rear tires.
fork_travelhas a correlation above .95 with: c(“rear_travel”, “fork_travel”). This make sense; for example,rear_travelshould be highly correlated withfork_travel.
In all, here are the most highly correlated variables (i.e. variables which have a correlation above .9 or below -.9):
mtb_correlation_df %>%
pivot_longer(-variable,
names_to = 'correlated_variable',
values_to = 'correlation') %>%
filter(variable != correlated_variable) %>%
# Sort by the absolute value of correlation
arrange(desc(abs(correlation))) %>%
filter((correlation > .90) | (correlation < -.90)) %>%
# Get rid of duplicative rows
dplyr::distinct(correlation, .keep_all = T) %>%
pander()| variable | correlated_variable | correlation |
|---|---|---|
| f_piston | r_piston | 1 |
| rear_travel | fork_travel | 0.9608 |
| rear_travel | wheelbase | 0.9301 |
| rear_travel | head_angle | -0.9219 |
| fork_travel | wheelbase | 0.9195 |
| fork_travel | head_angle | -0.9193 |
| head_angle | seat_angle | -0.9031 |
There are a lot, especially given that we only have 18 continuous columns in our dataset! For now, we’ll opt to include everything. But later on, as we analyze the importance of different features, we’ll look to remove some of the above variables first.
2. Principal Component Analysis (PCA)
Next, we’ll apply PCA to our dataset. In so doing, we’ll have to center and scale our data given how different the ranges are for certain measurements. Let’s take a look at our 5 principal components which explain the largest proportion of variance in the data:
# Impute missing values with column mean (not really best practice, but good enough)
for (c in 1:ncol(new_mtb_data)){
if (is.numeric(unlist(new_mtb_data[,c]))){
# print(colnames(new_mtb_data)[c])
new_mtb_data[is.na(new_mtb_data[,c]), c] <- mean(unlist(new_mtb_data[,c]), na.rm=TRUE)
}
}
mtb_no_null <- new_mtb_data %>%
select(-price) %>%
select_if(is.numeric) %>%
bind_cols(label = new_mtb_data$label) %>%
drop_na()
mtb_pca <- prcomp(mtb_no_null %>% select(-label),
center = TRUE,
scale. = TRUE)
# Put our summary results into a dataframe - Justin switching this to cbind() works for me, not sure why
mtb_pca_df <- tibble(variable = c('Standard Deviation', 'Proportion of Variance', 'Cumulative Proportion')) %>%
cbind(summary(mtb_pca)$importance)
mtb_pca_df %>%
# Only display the first 6 columns
select(c(variable:PC5)) %>%
pander()| variable | PC1 | PC2 | |
|---|---|---|---|
| Standard deviation | Standard Deviation | 3.024 | 1.262 |
| Proportion of Variance | Proportion of Variance | 0.538 | 0.09369 |
| Cumulative Proportion | Cumulative Proportion | 0.538 | 0.6317 |
| PC3 | PC4 | PC5 | |
|---|---|---|---|
| Standard deviation | 1.164 | 1.071 | 0.8761 |
| Proportion of Variance | 0.07977 | 0.06745 | 0.04515 |
| Cumulative Proportion | 0.7115 | 0.7789 | 0.8241 |
mtb_pca_df %>%
# Pivot our data so it's easier to visualize
pivot_longer(-variable,
names_to = 'PC',
names_prefix = 'PC') %>%
# Make the principal component column an integer so ggplot orders it from 1:17 properly
mutate(PC = as.integer(PC),
# Convert value to % (multiply by 100) so it's not a decimal
value = 100*value) %>%
filter(variable == 'Proportion of Variance') %>%
ggplot(aes(x = PC, y = value)) +
geom_point(size = 4, color = 'slateblue') +
geom_line(alpha = .6, lwd = 2, color = 'slateblue') +
labs(title = 'Proportion of Variance Explained by Principal Components',
x = 'Principal Component',
y = 'Proportion of Variance (%)')We can see that, actually, that our 1st principal component alone explains more than half our data. Starting at the 2nd principal component, there’s a distinguishable elbow point. After that, we have a huge drop-off. Starting at our 5th principal component, nearly 82.4% of the data’s variation is properly explained. This leads us to believe that the majority of the variation in our data can be explained by using just 1 principal component!
Let’s take a look at how our top 2 principal components explain the 5 different mountain bike categories:
p_load(devtools,
ggbiplot)
ggbiplot(mtb_pca,
obs.scale = 1,
var.scale = 1,
groups = mtb_no_null$label,
ellipse = TRUE,
circle = FALSE,
ellipse.prob = .5) +
theme(legend.direction = 'horizontal',
legend.position = 'top')# jpeg('../Images/pca.jpg')Here we can see that our top 2 principal components, which explain roughly 63.2% of the variation in our data, are already pretty good representations for describing the different components in our dataset. Even so, the groupings are distinctly plotted on the 2-D graph.
Clustering
Because we are investigating the validity of mountain bike categories, one approach is to treat this dataset as unsupervised, stripping the bikes of their label and seeing if various clustering algorithms can re-create the 5 distinct labels.
K-Means
# How many clusters are necessary? 4?
mtb_numeric <- mtb_no_null %>%
select(-label)
mtb_standard_scaled <- scale(mtb_numeric)
mtb_numeric <- mtb_no_null %>%
select(-label)
mtb_numeric <- mtb_no_null %>%
select(-label)
clusters <- 1:10
dists <- c()
for (c in 1:10){
km <- kmeans(mtb_standard_scaled, centers=c, iter.max=1000)
dists <- c(dists, km$tot.withinss)
}
# jpeg('../Images/Kmeans.jpg')
# plot(clusters, dists, type='l', xlab='Clusters', ylab='Total Sum of Squared Euclidean Distances')
# Plot our results
tibble(clusters = clusters,
dists = dists) %>%
ggplot(aes(x = clusters, y = dists)) +
geom_point(size = 4, color = 'slateblue') +
geom_line(alpha = .6, lwd = 2, color = 'slateblue') +
labs(title = "K-Means Clustering of MTB Data",
subtitle = 'Method uses `tot.withinss` parameter to measure distances.',
x = 'Clusters',
y = 'Total Sum of Squared Euclidean Distances')# Let's see where these clusters would end up on the 2D PCA plot
mtb_pca_scaled <- prcomp(mtb_standard_scaled,
center = F,
scale. = F)
pca_2_scaled <- as.matrix(mtb_standard_scaled) %*% as.matrix(mtb_pca_scaled$rotation[,1:2])
pca_km_scaled <- kmeans(pca_2_scaled, centers=3, iter.max=1000)
# Bring our PCA and k-means clusters results into our dataset
new_mtb_data %>%
cbind(pca_2_scaled) %>%
mutate(# Create a feature for the long-version of the names
bike_category = case_when(
label == 'tr' ~ 'Trail',
label == 'xc' ~ 'Cross Country',
label == 'dc' ~ 'Downcountry',
label == 'am' ~ 'All Mountain',
label == 'en' ~ 'Enduro',
TRUE ~ 'red'
),
# Bring our clusters in as a factor
cluster = as.factor(pca_km_scaled$cluster)) %>%
# GG-plot our shit - lol
ggplot() +
geom_point(aes(x = PC1,
y = PC2,
color = cluster,
shape = bike_category),
alpha = .9,
size = 3) +
# Add our cluster centers in as well
geom_point(data = as_tibble(pca_km_scaled$centers) %>%
mutate(cluster = as.factor(c(1, 2, 3))),
aes(x = PC1,
y = PC2,
color = cluster),
shape = 10,
size = 7) +
# Color clusters accordingly
scale_color_manual(values = c('slateblue4', 'gray', 'slateblue1'), name = 'Cluster') +
labs(title = "K-Means Clustering of MTB Principal Components",
subtitle = 'Assigned clusters denoted by color;\nBike categories denoted by shape;\nCluster centers denoted by large cross-hairs shape.',
x = 'Principal Component 1',
y = 'Principal Component 2')#TODO let's look at this bottom cluster - both Niner bikes
# Niner has low reach numbers on its bikes - could be because we used the Medium for these!
# Based on PCA mapping, the blur tr, expic, Exie, Ripley, and Element all have less chainstay length, and less pistons?? wow, should we exclude piston count?? with more 2 piston bikes getting added, it evens out the average, so these aren't showing up as much anymoreAbove, we attempted to graph the 3 clusters created using top 2 principal components in our data. For example, we can see Cluster #1 on the right-hand side of the chart, mostly composed of Cross Country bikes (diamonds in the chart) and some Downcountry bikes (denoted by squares). Downcountry bikes also seem to be part of Cluster #2 (gray points), along with Trail bikes (denoted by squares with an ‘x’ in them) and some Enduro bikes (denoted by ‘+’). However, Trail bikes also feature heavily in Cluster #3 along with most of the Enduro bikes.
Overall, it’s clear that there is significant overlap between our Clusters, mainly along the Principal Component 1 axis; lending credence to the notion that our bikes can be differentiated along a single, continuous scale.
Note: In the bottom-right of the graph (PC2 < -4), we see two Niner bikes, almost acting as outliers. For a 5’10” rider Niner suggests a size Medium, which results in low reach numbers on its bikes. From Figure X, we see that Reach heavily corresponds with PC2, and thus these bikes appear lower on the visual.
Gaussian Mixture Model (GMM)
In this section, we’ll take a more probabilistic model to our clustering. That is, we’ll use a Guassian Mixture Model (GMM) to build out normally distributed subgroupings within our mountain bike dataset, where the densities of each of the subgroupings represents a probability that a bike belongs to that subgrouping. Unlike K-Means, which is a more centroid-based clustering method, GMM is more of a distribution-based clustering method.
Generally, what we expect to see is something like the following:
where, given a specific type of bike, we can predict the probability, \(p(x)\) that a bike belongs to a category like
Cross Country (xc) vs. Trail vs. Enduro.
p_load(ClusterR)
# Build our GMM model
mtb_gmm <- GMM(mtb_standard_scaled,
dist_mode = 'eucl_dist', # Distance metric to use during seeding of initial means clustering
seed_mode = 'random_subset', # How initial means are seeded prior to EM alg
km_iter = 10, # Num of iterations of K-Means alg
em_iter = 10, # Num of iterations of EM alg
verbose = T
)## gmm_diag::learn(): generating initial means
## gmm_diag::learn(): k-means: n_threads: 1
## gmm_diag::learn(): k-means: iteration: 1 delta: 8.90446
## gmm_diag::learn(): k-means: iteration: 2 delta: 5.50614e-34
## gmm_diag::learn(): generating initial covariances
## gmm_diag::learn(): EM: n_threads: 1
## gmm_diag::learn(): EM: iteration: 1 avg_log_p: -23.9741
## gmm_diag::learn(): EM: iteration: 2 avg_log_p: -23.9741
##
## time to complete : 0.000593375
mtb_gmm_pred <- predict(mtb_gmm, mtb_standard_scaled)
opt_gmm <- Optimal_Clusters_GMM(mtb_standard_scaled,
max_clusters = 20,
criterion = "BIC",
dist_mode = "eucl_dist",
seed_mode = "random_subset",
km_iter = 10,
em_iter = 10,
var_floor = 1e-10,
plot_data = T)Use the mclust package in R, which utilizes Bayesian Information Criterion (BIC) to optimize the number of clusters.
p_load(mclust)
mtb_gmm2 <- Mclust(mtb_standard_scaled)
#or specify number of clusters
# mb3 = Mclust(iris[,-5], 3)
# optimal selected model
# mtb_gmm2$modelName
# optimal number of cluster
# mtb_gmm2$G
# probality for an observation to be in a given cluster
# head(mtb_gmm2)
# get probabilities, means, variances
summary(mtb_gmm2, parameters = TRUE)## ----------------------------------------------------
## Gaussian finite mixture model fitted by EM algorithm
## ----------------------------------------------------
##
## Mclust XXX (ellipsoidal multivariate normal) model with 1 component:
##
## log-likelihood n df BIC ICL
## 1161.57 58 170 1632.864 1632.864
##
## Clustering table:
## 1
## 58
##
## Mixing probabilities:
## 1
## 1
##
## Means:
## [,1]
## rear_travel -0.00000000000000019689111
## fork_travel 0.00000000000000035334149
## f_piston 0.00000000000000003469447
## f_rotor_dim 0.00000000000000028449465
## r_piston 0.00000000000000003469447
## r_rotor_dim 0.00000000000000020816682
## head_angle -0.00000000000000062189837
## seat_angle 0.00000000000000244596010
## crank_length -0.00000000000000002059984
## stem_length -0.00000000000000018127860
## handlebar_width 0.00000000000000283171923
## reach -0.00000000000000025153490
## stack 0.00000000000000384414722
## wheelbase -0.00000000000000107552856
## chainstay_length -0.00000000000000310862447
## bb_height 0.00000000000000166793662
## standover_height -0.00000000000000101481323
##
## Variances:
## [,,1]
## rear_travel fork_travel f_piston f_rotor_dim r_piston
## rear_travel 0.98275862 0.90542451 0.59686735 0.72048043 0.59686735
## fork_travel 0.90542451 0.98275862 0.64002066 0.74091647 0.64002066
## f_piston 0.59686735 0.64002066 0.98275862 0.54894999 0.98275862
## f_rotor_dim 0.72048043 0.74091647 0.54894999 0.98275862 0.54894999
## r_piston 0.59686735 0.64002066 0.98275862 0.54894999 0.98275862
## r_rotor_dim 0.76237685 0.76930003 0.46223590 0.75043919 0.46223590
## head_angle -0.87039460 -0.87233866 -0.52580084 -0.67262343 -0.52580084
## seat_angle 0.67337295 0.66583328 0.40146319 0.59847143 0.40146319
## crank_length 0.09940833 0.09531759 0.06238773 -0.12832130 0.06238773
## stem_length -0.59384645 -0.62552642 -0.50296823 -0.37650158 -0.50296823
## handlebar_width 0.67446116 0.71505742 0.57195023 0.57185265 0.57195023
## reach 0.49403881 0.45761337 0.11577433 0.37908265 0.11577433
## stack 0.71512572 0.76565529 0.45894387 0.45696039 0.45894387
## wheelbase 0.86024327 0.84786028 0.43799910 0.65232144 0.43799910
## chainstay_length 0.38380489 0.36250590 0.28932445 0.36421097 0.28932445
## bb_height 0.68833300 0.72034666 0.49766442 0.50808412 0.49766442
## standover_height -0.17414814 -0.12462704 -0.26314391 -0.07846539 -0.26314391
## r_rotor_dim head_angle seat_angle crank_length stem_length
## rear_travel 0.76237685 -0.87039460 0.67337295 0.099408329 -0.59384645
## fork_travel 0.76930003 -0.87233866 0.66583328 0.095317595 -0.62552642
## f_piston 0.46223590 -0.52580084 0.40146319 0.062387729 -0.50296823
## f_rotor_dim 0.75043919 -0.67262343 0.59847143 -0.128321301 -0.37650158
## r_piston 0.46223590 -0.52580084 0.40146319 0.062387729 -0.50296823
## r_rotor_dim 0.98275862 -0.78866903 0.68712353 -0.056561189 -0.43544939
## head_angle -0.78866903 0.98275862 -0.77474947 0.030011320 0.59600333
## seat_angle 0.68712353 -0.77474947 0.98275862 -0.086338652 -0.55311673
## crank_length -0.05656119 0.03001132 -0.08633865 0.982758621 -0.05505259
## stem_length -0.43544939 0.59600333 -0.55311673 -0.055052590 0.98275862
## handlebar_width 0.57752474 -0.68167799 0.54544535 0.068922889 -0.60398692
## reach 0.39938148 -0.52003884 0.48460989 0.006127947 -0.29705806
## stack 0.59385205 -0.68877269 0.60385363 0.109459988 -0.65775000
## wheelbase 0.71718120 -0.89225975 0.72239633 -0.039768314 -0.58551748
## chainstay_length 0.24060522 -0.30252811 0.18949583 -0.026718093 -0.16040798
## bb_height 0.46080162 -0.58245584 0.43202847 0.124547451 -0.53281576
## standover_height -0.16756962 0.19061326 -0.33385239 -0.002223620 0.34531612
## handlebar_width reach stack wheelbase
## rear_travel 0.67446116 0.494038811 0.71512572 0.86024327
## fork_travel 0.71505742 0.457613370 0.76565529 0.84786028
## f_piston 0.57195023 0.115774332 0.45894387 0.43799910
## f_rotor_dim 0.57185265 0.379082653 0.45696039 0.65232144
## r_piston 0.57195023 0.115774332 0.45894387 0.43799910
## r_rotor_dim 0.57752474 0.399381484 0.59385205 0.71718120
## head_angle -0.68167799 -0.520038840 -0.68877269 -0.89225975
## seat_angle 0.54544535 0.484609887 0.60385363 0.72239633
## crank_length 0.06892289 0.006127947 0.10945999 -0.03976831
## stem_length -0.60398692 -0.297058061 -0.65775000 -0.58551748
## handlebar_width 0.98275862 0.300899559 0.61183862 0.61735577
## reach 0.30089956 0.982758621 0.47915089 0.66688223
## stack 0.61183862 0.479150893 0.98275862 0.74843836
## wheelbase 0.61735577 0.666882228 0.74843836 0.98275862
## chainstay_length 0.35823973 -0.054976934 0.20008222 0.29271025
## bb_height 0.69345298 0.306785474 0.58120905 0.58965337
## standover_height -0.25299276 -0.091521624 -0.09390652 -0.08477310
## chainstay_length bb_height standover_height
## rear_travel 0.38380489 0.6883330 -0.17414814
## fork_travel 0.36250590 0.7203467 -0.12462704
## f_piston 0.28932445 0.4976644 -0.26314391
## f_rotor_dim 0.36421097 0.5080841 -0.07846539
## r_piston 0.28932445 0.4976644 -0.26314391
## r_rotor_dim 0.24060522 0.4608016 -0.16756962
## head_angle -0.30252811 -0.5824558 0.19061326
## seat_angle 0.18949583 0.4320285 -0.33385239
## crank_length -0.02671809 0.1245475 -0.00222362
## stem_length -0.16040798 -0.5328158 0.34531612
## handlebar_width 0.35823973 0.6934530 -0.25299276
## reach -0.05497693 0.3067855 -0.09152162
## stack 0.20008222 0.5812090 -0.09390652
## wheelbase 0.29271025 0.5896534 -0.08477310
## chainstay_length 0.98275862 0.3660130 0.18422861
## bb_height 0.36601298 0.9827586 -0.21028726
## standover_height 0.18422861 -0.2102873 0.98275862
plot(mtb_gmm2, 'classification')Multi-class SVM
If we were to treat our labels as truth, then we can approach this analysis as a supervised learning model. For this section, we chose to group the All Mountain Category in with Enduro, since it was completely overlapped on the PCA chart above. We also chose to switch around the categorization of the Downcountry category, leaving it as a separate category and grouping it with both Trail and XC to experiment with the results of the model.
We chose to use a Multi-Class Support Vector Machine, and a grid search to tune the kernel functions and \(\gamma\) values. For each set of parameters, we used K-fold cross validation with k=10 on all rows of the data. We decided against holding out data as a test set since we have such limited data, and the K-fold CV should evaluate the model’s performance on blind data.
Using all of the data, the best SVM model was 73% accurate, using a Radial Basis kernel function with \(\gamma=2.595024\)
Treating the Downcountry category as XC, the best model was 81.6% accurate, with a Radial Basis kernel function with \(\gamma=0.02983647\)
Treating the Downcountry category as Trail, the best model was 80.0% accurate with a Radial Basis kernel function with \(\gamma=3.764936\)
Of course, grouping this category with one of its adjacent categories we expect to see an increase in performance, but this could suggest that the Downcountry category is slightly more skewed towards the XC bikes.
p_load(e1071,
caret)
#convert all mountain category to enduro, dc -> Xc?
remap <- function(x, num){
if (x=='am' || x=='en'){
if (num){
return(4)
}
else{
return('Enduro')
}
}
else if(x=='xc' || x=='dc'){
if(num){
return(1)
}
else{
return('Cross Country')
}
}
# else if(x=='dc'){
# if(num){
# return(2)
# }
# else{
# return('Downcountry')
# }
# }
else if(x=='tr'){
if(num){
return(3)
}
else{
return('Trail')
}
}
}
labels <- as.factor(unlist(lapply(new_mtb_data$label, remap, F)))
trainSVM <- function(x, y, idx, k='radial basis', g=0){
xtest <- x[idx,]
xtrain <- x[-idx,]
ytest <- y[idx]
ytrain <- y[-idx]
if(k=='linearl'){
clf <- svm(x=xtrain, y=ytrain, kernel=k)
}
else{
if (g==0){
clf <- svm(x=xtrain, y=ytrain, kernel=k)
}
else{
clf <- svm(x=xtrain, y=ytrain, kernel=k, gamma=g)
}
}
preds <- predict(clf, xtest)
acc <- 0
cm <- table(ytest, preds)
for (i in 1:length(unique(labels))){
acc <- acc + cm[i,i]
}
return(acc/sum(cm))
}
# Roughly 66.6% accuracy when treating down country as separate category
# But - roughly 68.8% accuracy when treating down country as XC, only 69% accuracy when treating downcountry as trail, suggests that downcountry bikes are more akin to trail than they are XCfolds <- createFolds(labels, k=10)
#Grid Search for SVM
kernels <- c('linear', 'polynomial', 'radial', 'sigmoid')
gammas <- seq(-5, 3, length.out=100)
gammas <- 10^gammas
#Change these below
# X = pca_2_scaled
X = mtb_standard_scaled
y = labels
results <- matrix(ncol=3, nrow=0)
colnames(results) <- c('acc', 'kernel', 'gamma')
for (k in kernels){
if (k=='linear'){
folds <- createFolds(labels, k=10)
accs <- c()
for (fold in folds){
# print('here')
acc <- trainSVM(X, y, fold, k='linear', g=0)
accs <- c(accs, acc)
}
results <- rbind(results, c(mean(accs), k, 0))
}
else{
for (g in gammas){
# print('choosing gamma')
# print(k)
folds <- createFolds(labels, k=10)
accs <- c()
for (fold in folds){
acc <- trainSVM(pca_2_scaled, labels, fold, k=k, g=0)
accs <- c(accs, acc)
}
results <- rbind(results, c(mean(accs), k, g))
}
}
}
results <- data.frame(results)
results$acc <- as.numeric(results$acc)
results$gamma <- as.numeric(results$gamma)
results[which.max(results$acc), ]## acc kernel gamma
## 109 0.8180952 radial 0.0000367838
nonlinear_svm <- results[-(results$kernel=='linear'), ]
nonlinear_svm[which.max(nonlinear_svm$acc), ]## acc kernel gamma
## 109 0.8180952 radial 0.0000367838
# On two axis, the best svm model is linearTo visualize the SVM, we again mapped all features to the 2 Principal Components. In this scenario, we actually acheived a higher accuracy of 75% using a linear kernel, again treating the Downcountry category as its own distinct category.
## This cell only to visualize linear kernel
pcsvm <- svm(x=pca_2_scaled, y=labels, kernel='linear', gamma=0.2782559 )
dat <- data.frame(pca_2_scaled)
grid <- expand.grid(seq(min(dat[, 1]),max(dat[,1]),length.out=100),seq(min(dat[,2]),max(dat[,2]),length.out=100))
names(grid) <- names(dat)[1:2]
preds <- predict(pcsvm, grid)
df <- data.frame(grid, preds)
ggplot(df, aes(x = PC1, y = PC2)) +
geom_tile(aes(fill=preds)) +
geom_point(data = dat, aes(shape = labels), size = 2) +
labs(title = "Support Vector Machine Classification",
x = 'Principal Component 1',
y = 'Principal Component 2')An interesting observation is that most of the boundary lines are more or less vertical, suggesting that most of the variation between classes is along Principal Component 1. We see this deviate between the XC and Downcountry boundary, however the validity of this boundary is still in question since the Downcountry category itself is more or less unofficial.
# DC as XC, using Linear
pcsvm2 <- svm(x=pca_2_scaled, y=labels, kernel='linear')
preds2 <- predict(pcsvm2, grid)
df2 <- data.frame(grid, preds2)
ggplot(df2, aes(x = PC1, y = PC2)) +
geom_tile(aes(fill=preds2)) +
geom_point(data = dat, aes(shape = labels), size = 2) +
labs(title = "Support Vector Machine Classification",
x = 'Principal Component 1',
y = 'Principal Component 2') Mapping all Downcountry bikes to XC, the boundaries become almost entirely vertical, again suggesting that the classification of bikes can be attributed to Principal Component 1.
Conclusions
Findings
All results suggest that trying to discretely categorize full suspension mountain bikes is more or less arbitrary.
The categorization of a mountain bike should be treated as a continuous scale, with Cross Country bikes on one end and Enduro bikes on another.
To obtain where a specific bike lies on this scale, one can use the linear combination of the bike’s specifications and the first principle component.
This new spectrum of mapping bikes can provide bike manufacturers and consumers quantify how a bike will handle.
Let’s look at an example from the data above. Some bike companies, like Transition and Revel, do not explicitly categorize their bikes like others do. For these brands, we categorized them based on general attributes, as well as media coverage of them.
| Rear Travel | Fork Travel | Front Piston | Front Rotor Diameter | Rear Piston | Rear Rotor Diameter | Head Angle | Seat Angle | Crank Length | Stem Length | Handlebar Width | Reach | Stack | Wheelbase | Chainstay Length | Bottom Bracket Height | Standover Height |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 115 | 120 | 2 | 180 | 2 | 160 | 67.5 | 75.3 | 170 | 40 | 780 | 473 | 619 | 1194 | 436 | 338 | 699 |
Converting to an input vector: \[ \text{Ranger} = \begin{bmatrix} 115 \\ 120 \\ 2 \\ 180 \\ 2 \\ 160 \\ 67.5 \\ 75.3 \\ 170 \\ 40 \\ 780 \\ 473 \\ 619 \\ 1194 \\ 436 \\ 338 \\ 699 \end{bmatrix} \rightarrow \text{ Ranger (scaled)} = \begin{bmatrix} -0.61 \\ -0.80 \\ -1.68 \\ -0.53 \\ -1.68 \\ -1.30 \\ 0.79 \\ -0.39 \\ -0.40 \\-1.15 \\-0.11 \\0.60 \\0.16 \\-0.33 \\0.16 \\-0.16 \\ -1.01 \end{bmatrix} \text{and PC1}=\begin{bmatrix} -0.31 \\ -0.31 \\ -0.23 \\ -0.26\\ -0.23\\ -0.27\\ 0.30\\ -0.26\\ -0.01\\ 0.24\\ -0.27\\ -0.17\\ -0.26\\ -0.30\\ -0.13\\ -0.25\\ 0.08\end{bmatrix}\]
\[ \text{Ranger} \times \text{PC1} = 1.7\]
Mapping the Revel Ranger to its first Principal Component we get a value of 1.7 which puts us right around the boundary between Trail and XC, which lines up with the PinkBike editors’ labelling of Downcountry in the video linked above.
# #Get Ranger stats
# mtb_numeric['ranger',]
#
# # Get Scaled Ranger
# length(mtb_standard_scaled['ranger', ])
# length(as.matrix(mtb_pca_scaled$rotation[,1]))
# # Get PC 1
#
# round(mtb_standard_scaled['ranger', ] %*% as.matrix(mtb_pca_scaled$rotation[,1]),2)Opportunities for Improved Analysis
There are a few opportunities to improve the analysis included in this presentation and forthcoming report:
Inclusion of more bikes (rows) | More rows = more robust clustering algorithms.
Inclusion of more bike features (columns) | Although we included the most meaningful specs/geometry of the bikes analyzed, there are dozens of other, smaller features that can be used to help differentiate between different types of bikes.
Include all sizes of bikes | We chose to use the size that corresponded to a 5’10” rider, but some bike manufacturers could interpret this as a Medium and others a Large.